<template>
  <div class="v-editor-model-right-dropdown g-jc-sb">
    <div
      class="g-pd-l-8"
      @contextmenu="propertyModelContextMenu($event, valueData as ModelValue)"
    >
      <template v-if="valueData && valueData.icon">
        <img
          class="g-m-r-4 g-relative g-t-2"
          style="top: -1px; height: 16px"
          :src="valueData.icon"
        />
        <span v-if="valueData && valueData.name">{{ valueData.name }}</span>
      </template>
    </div>

    <div
      v-if="selected && !row.readonly && !isModelDisabled"
      class="g-pd-r-4"
    >
      <MDropdown
        lazy
        :loadListCallback="loadOptions"
      >
        <div>
          <img
            v-if="isVireState"
            src="statics/icons/app/iconlist2.png"
            class="g-pointer"
          />
          <img
            v-else
            src="statics/icons/app/iconmore.png"
            class="g-pointer"
          />
        </div>
        <template #dropdown>
          <MDropdownMenuItem
            v-for="(item, index) in selectOptions"
            :key="index"
            :selected="isSelected(item)"
            @click="handleClickOption(item)"
          >
            <div>
              <img
                v-if="item.icon"
                :src="item.icon"
                style="height: 16px; width: 16px"
              />
              <span
                class="g-pd-lr-8"
                :style="{ 'margin-left': item.icon ? 0 : '20px' }"
              >
                {{ locale.getTByContent(item, item.label, { en: "enLabel", zhCn: "label" }) }}
              </span>
            </div>
            <el-icon
              v-if="isVireState && item.label !== '空'"
              :class="{ 'g-disabled': !isSelected(item) }"
              class="edit-icon"
              @click.stop="isSelected(item) && editParams(valueData.id, valueData.name)"
            >
              <Edit />
            </el-icon>
          </MDropdownMenuItem>
        </template>
      </MDropdown>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { PropertyRow, ModelValue, AddModelItem } from "../../types";
import { ref, Ref, computed, watch, inject } from "vue";
import MDropdown from "@/common/dropdown/Dropdown.vue";
import MDropdownMenuItem from "@/common/dropdown/DropdownMenuItem.vue";
import { propertyUtil } from "../../PropertyUtil";
import { propertyModelContextMenu } from "../propertyUtil";
import { locale } from "@/util/locale";
import { useLoadAddItems } from "../common/useLoadOptions";
import { PropertyKey } from "@/constants/Enums";
import { ModelData } from "@/constants/types";
import { modelService } from "@/modules/model/service";
import { archService } from "@/modules/model/service/ArchService";
import { Edit } from "@element-plus/icons-vue";
import { vireParamsWindow } from "@/config/customSystemConfig/customWindows/vireParams";
import { MetaclassType } from "@/constants/MetaclassType";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

/**
 * 右侧有个下拉菜单，选择模型类型
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
}>();

const valueData = computed(() => {
  return props.row.value as ModelValue;
});

const selectedModelId = ref("");

const getItems = async (): Promise<AddModelItem[]> => {
  const row = props.row;
  if (isVireState.value) {
    const modelIds = await archService.vireSelectableItems(app.activeProjectId, row.modelId);
    if (modelIds.length > 0) {
      const modelDatas = await modelService.getModelDatas(app.activeProjectId, modelIds);
      return modelDatas.map(model => {
        return {
          icon: model.icon,
          metaClass: model.id,
          label: model.name,
          applyStereotypes: model.sts,
          enLabel: model.name
        };
      });
    } else {
      return [];
    }
  } else {
    const res = await modelService.getPropertyAddModelItems(app.activeProjectId, row.modelId, row.modelIds, row.key);
    return res;
  }
};

const isSelected = (item: AddModelItem) => {
  return item.metaClass === (props.row.value as ModelData)?.sts[0];
};

const isVireState = computed(() => {
  const propertyList = app.activeProject?.attributeTabsModel.propertyPaneModel.tableData || [];
  const appliedStereotypeValue =
    (propertyList.find(item => item.key === PropertyKey.Element_appliedStereotype)?.value as ModelData[]) || [];

  return appliedStereotypeValue.some(item => item.id === "78901028983058816");
});

const { addModelItems, loadOptions, clear } = useLoadAddItems(props.row, getItems);

watch(() => props.selected, clear);

const selectOptions = computed<AddModelItem[]>(() => {
  const data = (addModelItems.value || []).filter(Boolean);
  if (props.row.value) {
    data.unshift({ metaClass: "", label: "空", enLabel: "Null", applyStereotypes: [], icon: "" });
  }
  return data;
});

watch(
  () => props.selected,
  val => {
    if (val === false) {
      selectedModelId.value = "";
    }
  }
);

async function handleClickOption(option: AddModelItem) {
  if (option.metaClass === "") {
    // TODO 删除属性
    if (valueData.value?.id) {
      propertyUtil.deletePropertyAndRefresh(props.row, valueData.value.id);
    }
  } else {
    if (isVireState.value) {
      const modelId = await archService.vireUpdateDoActivity(app.activeProjectId, props.row.modelId, option.metaClass);
      const childrenModels = await modelService.getChildModelDatas(app.activeProjectId, modelId);
      const stateMachineModel = childrenModels.find(item => item.metaclass === MetaclassType.StateMachine);
      if (stateMachineModel) {
        editParams(stateMachineModel.id, stateMachineModel.name);
      }
    } else {
      propertyUtil.updatePropertyAndFresh(props.row, option.metaClass);
    }
  }
}

const editParams = (modelId: string, elementName: string) => {
  vireParamsWindow.popup({ projectId: app.activeProjectId, modelId, elementName });
};
</script>
<style lang="scss" scoped>
.edit-icon {
  color: #747ad0;
  font-size: 14px;
}
</style>
